/**
 * Created by linyi on 2019/3/6
 */
import React from 'react'
import { TreeSelect } from 'antd'
import groupBy from 'lodash/groupBy'

class ShopSelector extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      choices: []
    }
  }

  componentDidMount() {
    const accountInfo = localStorage.getItem('account')
    const { organizations } = JSON.parse(accountInfo) || {}
    // 按照 purchaseOrg / shopGroup 进行层级划分 形成树结构
    const choices = Object.entries(
      groupBy(organizations, ele => ele.purchaseOrgCode)
    )
      .map(([key, val]) => ({
        purchaseOrgCode: key,
        purchaseOrgId: val[0].purchaseOrgId,
        purchaseOrgName: val[0].purchaseOrgName,
        value: key,
        title: `${key} ${val[0].purchaseOrgName}`,
        children: val
      }))
      .map(({ children, ...pass }) => {
        const ch = Object.entries(
          groupBy(children, item => item.shopGroupCode)
        ).map(([key, val]) => ({
          shopGroupCode: key,
          shopGroupId: val[0].shopGroupId,
          shopGroupName: val[0].shopGroupName,
          value: key,
          title: `${key} ${val[0].shopGroupName}`,
          children: val.map(ele => ({
            ...ele,
            value: ele.locationCode,
            title: `${ele.locationCode} ${ele.locationShortName}`
          }))
        }))

        return { ...pass, children: ch }
      })
    this.setState({ choices })
  }

  render() {
    const { choices } = this.state

    return (
      <TreeSelect
        allowClear
        treeData={choices}
        treeCheckable
        placeholder="请选择门店"
        dropdownStyle={{
          maxHeight: '300px'
        }}
        {...this.props}
      />
    )
  }
}

ShopSelector.propTypes = {
  ...TreeSelect.propTypes
}

ShopSelector.defaultProps = {
  ...TreeSelect.defaultProps
}

export default ShopSelector
